<template>
    <div class="app-container">

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model="queryParams.title" placeholder="请输入" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="新闻分类" prop="classId">
          <el-select v-model="queryParams.classId" placeholder="请选择" clearable>
            <el-option v-for="dict in classifyList" :key="dict.classId" :label="dict.className" :value="dict.classId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
      </el-row>
  
      <el-table v-loading="loading" :data="areaList">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="新闻标题" align="center" prop="title" />
        <el-table-column label="新闻分类" align="center" prop="className" />
        <el-table-column label="分类排序" align="center" prop="sortBy" />
        <el-table-column label="新闻类型" align="center" prop="newsType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.news_type" :value="scope.row.newsType" />
          </template>
        </el-table-column>
        <el-table-column label="新闻状态" align="center" prop="statu">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.new_status" :value="scope.row.statu" />
          </template>
        </el-table-column>
        <el-table-column label="新闻封面图" align="center" prop="coverUrls">
          <template slot-scope="scope">
            <div v-if="scope.row.newsType == 'article'">
              <el-image v-if="scope.row.coverUrls.length" v-for="(img,index) in scope.row.coverUrls" :key="index" :src="img.url" style="width: 60px;height: 60px;margin-left:5px" :preview-src-list="[img.url]" />
            </div>
            <p v-else>无</p>
          </template>
        </el-table-column>
        <el-table-column label="视频" align="center" prop="video">
          <template slot-scope="scope">
            <div>
                <video v-if="scope.row.newsType == 'video'" :src="scope.row.video" controls width="100px" style="width: 100px;max-height:200px" />
                <p v-else>无</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="视频海报图" align="center" prop="videoPoster">
          <template slot-scope="scope">
            <div v-if="scope.row.newsType == 'video'">
              <el-image v-if="scope.row.videoPoster.length" v-for="(img,index) in scope.row.videoPoster" :key="index" :src="img.url" style="width: 60px;height: 60px;margin-left:5px" :preview-src-list="[img.url]" />
            </div>
            <p v-else>无</p>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="100" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete"@click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="新闻标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="新闻分类" prop="classId">
            <el-select v-model="form.classId" placeholder="请选择" clearable>
              <el-option v-for="dict in classifyList" :key="dict.classId" :label="dict.className" :value="dict.classId" />
            </el-select>
          </el-form-item>
          <el-form-item label="分类排序">
            <el-input v-model="form.sortBy" placeholder="请输入" oninput="value=value.replace(/^0+(\d)|[^\d]+/g,'')" style="width: 217px;" />
          </el-form-item>
          <el-form-item label="新闻类型" prop="newsType">
            <el-select v-model="form.newsType" placeholder="请选择" clearable>
              <el-option v-for="dict in dict.type.news_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="新闻状态" prop="statu">
            <el-select v-model="form.statu" placeholder="请选择" clearable>
              <el-option v-for="dict in dict.type.new_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="新闻封面图" prop="coverUrls" v-if="form.newsType === 'article'">
            <image-drap-upload v-model="form.coverUrls" :limit="3"  />
          </el-form-item>
          <el-form-item label="新闻海报图" prop="videoPoster" v-if="form.newsType === 'video'">
            <image-drap-upload v-model="form.videoPoster" :limit="1"  />
          </el-form-item>
          <el-form-item label="新闻视频" prop="video" required v-if="form.newsType === 'video'">
            <el-upload accept=".mp4,.flv,.avi,.wmv,.rmvb"
                class="avatar-uploader" :action="uploadImgUrl" :show-file-list="false" :on-success="handleVideoSuccess"
                :before-upload="beforeVideoUpload" name="file" :headers="{saasToken: saasToken, Develop: 'prod'}" :http-request="handleRequest" :with-credentials="true">
                <video v-if="form.video" :src="form.video" controls="controls" class="video-box" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <el-progress v-if="showProgress" :percentage="progressPercent" :status="progressStatus"></el-progress>
            </el-upload>
          </el-form-item>
          <el-form-item label="新闻内容" prop="details" v-if="form.newsType !== 'video'">
            <div style="border: 1px solid #ccc" v-if="open">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
              <Editor style="height: 420px; overflow-y: hidden;" v-model="form.details" :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
    
<script>
import { Debounce } from '@/utils/tools.js'
import { getSassToken } from "@/utils/utils";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { getNewsList, newsInsert, getNewsDetail, getClassifyList, newsDelete, newsModify } from "@/api/news/news";
import imageDrapUpload from '@/components/Upload';
import md5 from 'js-md5';
import dayjs from 'dayjs';
import { uploadFile } from "@/api/uploadFile";
export default {
name: "productCate",
components: {
    Editor,
    Toolbar,
    imageDrapUpload
},
dicts: ["news_type","news_who_see","new_status"],
// dict.type.
data() {
    return {
        uploadImgUrl: process.env.VUE_APP_UPLOAD_API + "/file/uploadFile",
        // 富文本
        editor: null,
        toolbarConfig: {},
        uploadFileSize: false,
        editorConfig: { 
            placeholder: "请输入内容...",
            MENU_CONF: {
              uploadImage: {
                  maxFileSize: 10 * 1024 * 1024, // 10M
                  timeout: 60 * 1000, // 60 秒
                  server:  process.env.VUE_APP_UPLOAD_API + "/common/saasapi/uploadFileAli",
                  headers: {
                  Develop: 'prod',
                  SaasToken: getSassToken()
                  },
                  fieldName: 'files',
                  customInsert(res, insertFn) {
                      // 上传图片
                      let url = res.data && res.data[0].browseUrl || ''
                      let alt = ''
                      let href = res.data && res.data[0].browseUrl || ''
                      insertFn(url, alt, href)
                  },
                  onProgress:(progress) => {
                    this.$modal.loading("正在上传图片，请稍候...");
                  },
                  // 单个文件上传成功之后
                  onSuccess:(file)=> {
                    this.$modal.msgSuccess("图片上传成功");
                    this.$modal.closeLoading();
                  },
                  // 单个文件上传失败
                  onFailed:() => {
                    this.$modal.msgError("上传图片失败，请重试");
                    this.$modal.closeLoading();
                  },
              },
              uploadVideo: {
                  maxFileSize:100 * 1024 * 1024 ,
                  timeout: 120 * 1000, // 15 秒
                  server:  process.env.VUE_APP_UPLOAD_API + "/common/saasapi/uploadFileAli",
                  headers: {
                  Develop: 'prod',
                  SaasToken: getSassToken()
                  },
                  fieldName: 'files',
                  customInsert(res, insertFn) {
                      // 上传图片
                      let url = res.data && res.data[0].browseUrl || ''
                      let alt = ''
                      let href = res.data && res.data[0].browseUrl || ''
                      insertFn(url, alt, href)
                  },
                  onBeforeUpload:(file)=> {
                    // let val; 
                    // for(var key in file){
                    //   val=file[key];
                    //   break;
                    // }
                    // if(val.size > 15 * 1024 * 1024){
                    //   this.$modal.msgError("文件太大,请上传更小的视频文件...");
                    // }
                    return file
                  },
                  onProgress:(progress) => {
                    this.$modal.loading("正在上传文件，请稍候...");
                  },
                  // 单个文件上传成功之后
                  onSuccess:(file)=> {
                    this.$modal.msgSuccess("视频上传成功");
                    this.$modal.closeLoading();
                  },
                  // 单个文件上传失败
                  onFailed:() => {
                    this.$modal.msgError("上传文件失败，请重试");
                    this.$modal.closeLoading();
                  },
              }
            }
        },
        mode: "default", // or 'simple'
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 订单表格数据
        areaList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNo: 1,
          pageSize: 10
        },
        // 表单参数
        form: {
          classId: null,
          title: null,
          newsType: null,
          details: null,
          coverUrls: null,
          sortBy: null,
          videoPoster: null,
          statu: 0
        },
        // 表单校验
        rules: {
          title: [
              { required: true, message: "请输入新闻标题", trigger: "blur" },
          ],
          classId: [
              { required: true, message: "请选择新闻分类", trigger: "change" },
          ],
          newsType: [
              { required: true, message: "请选择新闻类型", trigger: "change" },
          ],
          statu: [
              { required: true, message: "请选择新闻状态", trigger: "change" },
          ],
          coverUrls: [
              { required: true, message: "请上传新闻封面图", trigger: "change" },
          ],
          details: [
              { required: true, message: "请输入新闻内容", trigger: "blur" },
          ],
          video: [
              { required: true, message: "请上传新闻视频", trigger: "blur" },
          ],
          videoPoster: [
              { required: true, message: "请上传新闻海报图", trigger: "change" },
          ],
        },
        classifyList:[],//分类
        progressPercent: 0,
        progressStatus: null,
        showProgress: false,
        saasToken: ''
    };
},
created() {
    this.getList();
    this.getClassifyListData()
    let date = dayjs().format('YYYYMMDD')
    let saasToken = date + 'MNAc1qMEyQXauIVckovoh5gklhQnziyZ' + 2
    this.saasToken = md5(saasToken)
    this.getList();
},
methods: {
    getClassifyListData(){
      let parmas = {
        pageNo: 1,
        pageSize: 200
      }
      getClassifyList(parmas).then(res => {
        if(res.code === 200){
          this.classifyList = res.data.records
        }
      })
    },
    onCreated(editor) {
        this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    /** 查询列表 */
    getList() {
        this.loading = true;
        getNewsList(this.queryParams).then((res) => {
          res.data.records.forEach(item => {
            if(item.coverUrls){
              let arr = item.coverUrls.split(',');
              let arrs = []
              arr.forEach(path => {
                let obj = {url:''}
                obj.url = path
                arrs.push(obj)
              })
              item.coverUrls = arrs
            }
            item.videoPoster = item.videoPoster ? [{'url':item.videoPoster}] : [];
          })
          this.areaList = res.data.records;
          this.total = res.data.total;
          this.loading = false;
        });
    },
    /** 新增按钮操作 */
    handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加新闻";
    },
    /** 修改按钮操作 */
    handleUpdate:Debounce(function (row) {
        this.reset();
        getNewsDetail(row.newsId).then(res => {
          this.form = res.data;
          if(res.data.coverUrls){
            let arr = res.data.coverUrls.split(',');
            let arrs = []
            arr.forEach(path => {
              let obj = {url:''}
              obj.url = path
              arrs.push(obj)
            })
            res.data.coverUrls = arrs
          }
          res.data.videoPoster = res.data.videoPoster ? [{'url':res.data.videoPoster}] : [];
          this.form.statu = this.form.statu+''
          this.open = true;
          this.title = "修改新闻";
        });
    },500),
    // 取消按钮
    cancel() {
        this.open = false;
        this.reset();
    },
    // 表单重置
    reset() {
        this.form = {};
        this.resetForm("form");
    },
    /** 删除按钮操作 */
    handleDelete:Debounce(function (row) {
        this.$modal.confirm('是否确认删除名称为"' + row.title + '"的新闻？').then(function() {
            return newsDelete(row.newsId);
        }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },500),
    /** 搜索按钮操作 */
    handleQuery() {
        this.queryParams.pageNo = 1;
        this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
    },
    /** 提交按钮 */
    submitForm:Debounce(function () {
        this.$refs["form"].validate((valid) => {
            if (valid) {

              if(!this.form.details){
                  this.$modal.msgWarning("请输入文章内容");
                  return
              }
              if(this.form.newsType === 'video' && !this.form.video){
                  this.$modal.msgWarning("请上传新闻视频");
                  return
              }

              let data = JSON.parse(JSON.stringify(this.form))
              if(data.coverUrls && data.coverUrls.length){
                data.coverUrls = (data.coverUrls.map(item => item.url)).join(',')
              }

              if(data.videoPoster && data.videoPoster.length){
                data.videoPoster = data.videoPoster[0].url
              }else{
                data.videoPoster = ''
              }
              
              if (this.form.newsId) {
                data.newsId = this.form.newsId;
                newsModify(data).then((response) => {
                  this.$modal.msgSuccess("编辑成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                newsInsert(data).then((response) => {
                  this.$modal.msgSuccess("添加成功");
                  this.open = false;
                  this.getList();
                });
              }
            }
        });
    },500),
    handleVideoSuccess(res, file) {

    },
    beforeVideoUpload(file) {
      console.log()
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) == -1) {
            this.$message.error('请上传正确的视频格式');
            return
        }
        const isLt2M = file.size / 1024 / 1024 < 200;
        if (!isLt2M) {
            this.$message.error('上传视频大小不能超过 200M!');
            return
        }
    },
    async handleRequest(data) {
        let formdata = new FormData();
        formdata.append('file', data.file);
        formdata.append('platform', 6);
        this.showProgress = true
        this.progressStatus = null;
        const config = {
            onUploadProgress: event => {
                // event.loaded:已上传文件大小
                // event.total:被上传文件的总大小
                this.progressPercent = Number((event.loaded / event.total * 100) | 0) > 98 ? 98 : Number((event.loaded / event.total * 100) | 0);
                console.log("progressPercent1", this.progressPercent)
            }
        };
        let uploadRes = await uploadFile(formdata, config);
        console.log('uploadRes',uploadRes);
        if (uploadRes.code == 200) {
            this.progressPercent = 0;
            this.showProgress = false
            this.progressStatus = 'success';
            this.$set(this.form, 'video', uploadRes && uploadRes.data)
            this.$message({
                type: 'success',
                message: "上传成功",
            });
        } else {
            this.progressPercent = 0;
            this.showProgress = false
            this.$message({
                type: 'error',
                message: "上传失败",
            });
        }
    },
},
};
</script>
<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.video-box {
    width: 100%;
    max-height: 400px;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

</style>